<template>
  <div class="_flex_column_">

    <Breadcrumb></Breadcrumb>

    <!--搜索框-->
    <a-form
        ref="defSearch"
        :model="search.def"
        :rules="search.defRules"
        layout="inline"
        class="_search_from_">

      <a-form-item label="ID" name="id" class="_230w">
        <a-input v-model:value="search.def.id" placeholder="请输入唯一ID" :allowClear="true"></a-input>
      </a-form-item>

      <a-form-item label="状态" name="menu_is_show" class="_180w">
        <a-select v-model:value="search.def.menu_is_show" placeholder="是否展示" :allowClear="true">
          <a-select-option v-for="(item,index) in option.menuIsSHow" :value=item.key>
            {{
              item.text
            }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="链接类型" name="link_type" class="_230w">
        <a-select v-model:value="search.def.link_type" placeholder="链接类型" :allowClear="true">
          <a-select-option v-for="(item,index) in option.menuLinkType" :value=item.key>
            {{
              item.text
            }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <div style="flex: 1 1 0;"/>

      <a-form-item style="margin-right: 0">
        <a-button type="primary" @click="queryPage_">查询</a-button>
        <a-button style="margin-left: 10px" @click="()=>{ resetForm_('defSearch'); }">重置</a-button>
      </a-form-item>
      <!--      <el-form-item>-->
      <!--        <el-button type="primary" @click="queryPage_">查询</el-button>-->
      <!--        <el-button @click="()=>{ resetForm_('searchForm'); queryPage_() }">重置</el-button>-->
      <!--      </el-form-item>-->
      <!--    </el-form>-->

    </a-form>

    <!--表格选项-->
    <div class="_tools_">
      <div style="color: rgba(0,0,0,.85);font-size: 16px;">区域地图</div>

      <div style="flex: 1 1 0"></div>

      <a-button type="primary" size="small" ghost>新建</a-button>

      <a-divider type="vertical"/>

      <a-tooltip placement="top">
        <template #title>
          <span>批量删除</span>
        </template>
        <delete-outlined :style="{fontSize: '16px'}"/>
      </a-tooltip>

      <a-tooltip placement="top">
        <template #title>
          <span>表格大小</span>
        </template>
        <a-dropdown :trigger="['click']">
          <setting-outlined :style="{fontSize: '16px'}" class="_magl14"/>
          <template #overlay>
            <a-menu v-model:selectedKeys="table.def.size" @click="(item)=>{table.def.size=item.key}">
              <a-menu-item v-for="(item,index) in option.tableSize" :key="item.key">
                <div style="padding: 0 5px">
                  {{ item.text }}
                </div>
              </a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>

      </a-tooltip>

      <a-tooltip placement="top">
        <template #title>
          <span>全 屏</span>
        </template>
        <fullscreen-outlined :style="{fontSize: '16px'}" class="_magl14" @click="fullScreen"/>
      </a-tooltip>
      <!--          <a style="margin-left: 10px">-->
      <!--            <file-add-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            新增</a>-->
      <!--          <a style="margin-left: 10px">-->
      <!--            <edit-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            编辑</a>-->
      <!--          <a style="margin-left: 10px;padding:2px;">-->
      <!--            <delete-outlined style="color: #1890FF;font-size: 10px;"/>-->
      <!--            删除</a>-->
    </div>

    <!--画布-->
    <a-row ref="canvasParent" style="height: 600px">
      <canvas id="canvas" style="border: 1px solid green;"/>
    </a-row>

  </div>
</template>

<script>

import {defineComponent} from 'vue';
import Breadcrumb from "@/common/layout/Breadcrumb.vue";

export default defineComponent({
  components: {Breadcrumb},
  mounted() {

    this.intiCanvas();

    this.queryAreaMap()

    window.onresize = () => {
      this.resizeCanvas()
    }
  },
  //数据
  data() {
    return {
      //搜索
      search: {

        //默认搜索
        def: {
          name: "",
          path: "",
          link_type: undefined,
          menu_is_show: undefined,
        },
        defRules: {},

        //功能搜索
        res: {
          menuId: "",
          menuName: "",
          name: undefined,
          api_name: undefined,
          request_url: undefined,
          type: undefined,
        },
        resRules: {},
      },
      //option选项
      option: {
        menuRes: [
          {key: '0', text: '按钮'},
          {key: '1', text: '非按钮'},
        ],
        tableSize: [
          {key: 'default', text: '大号'},
          {key: 'middle', text: '中号'},
          {key: 'small', text: '小号'},
        ],
        menuIsSHow: [
          {key: '0', text: '展示',},
          {key: '1', text: '隐藏'},
        ],
        menuLinkType: [
          {key: '0', text: '非链接'},
          {key: '1', text: '外部链接'},
          {key: '2', text: '内部链接'},
        ]
      },
      //开关
      show: {
        spinning: false,
      },
      canvas: null,
      canvasConfig: {
        width: 1200,
        height: 600,
        background: '#E4E6E3',
        defaultZoom: 1,
        mutiNum: 60,
        panning: false,
        data: {},
        trackLine: null,
        trackPosition: [{x: 10, y: 20}],
      }
    }
  },
  //方法
  methods: {
    queryAreaMap() {
      this.$http.post('/position/factory/map', {}).then((res) => {
        if (res.status) {
          let maps = [res.data.map]
          // maps.push(res.data.[0])
          maps.push(...res.data.area)
          maps.push(...res.data.store)
          maps.push(...res.data.road)
基础数据
          this.drawMap(maps)

          this.resizeCanvas()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    //绘制
    drawMap(datas) {
      for (let i = 0; i < datas.length; i++) {
        let data = datas[i]
        //console.log(data)
        let config = JSON.parse(data.config)
        let xyArray = JSON.parse(data.area_xy)
        //画区域
        let path
        if (config && config.showArea) {
          //console.log(1)
          let M_X = parseFloat(xyArray[0].x) * this.canvasConfig.mutiNum
          let M_Y = parseFloat(xyArray[0].y) * this.canvasConfig.mutiNum
          let pathStr = 'M ' + M_X + ' ' + (M_Y * -1)
          for (let i = 1; i < xyArray.length; i++) {
            let L_X = parseFloat(xyArray[i].x) * this.canvasConfig.mutiNum
            let L_Y = parseFloat(xyArray[i].y) * this.canvasConfig.mutiNum
            pathStr += ' L ' + L_X + ' ' + (L_Y * -1)
          }
          pathStr += ' z'
          path = new fabric.Path(pathStr)
          //console.log(2)
          path.set({
            fill: config.backgroundColor,
            selectable: true,
            hasControls: false,
            lockMovementX: true,
            lockMovementY: true,
            data: data,
            dataConfig: config
          })

          //配置边框
          if (config.showBorder) {
            path.stroke = config.borderColor//边框颜色
            path.strokeWidth = parseInt(config.borderSize)//边框宽度
          }
          this.canvas.add(path)
          //console.log(3)

          //向上到顶层
          if (config.isTop) {
            this.canvas.bringToFront(path)
          }

          //向下到底层
          if (config.isBottom) {
            this.canvas.sendToBack(path)
          }
          //console.log(4)

        }

        //加文字
        if (config && config.showArea && config.showText) {
          //console.log(5)

          //计算中心坐标
          let pathS = []
          for (let k = 0; k < path.path.length - 1; k++) {
            let path_ = path.path[k]
            pathS.push({x: path_[1], y: path_[2]})
          }
          //console.log(6)

          let centerPosition = this.$kit.centerPosition(pathS)
          //加字
          ////console.log(e.t_name)
          let rectText = new fabric.Textbox(data.name, {
            fontSize: config.textSize,
            fill: config.textColor,
            hasControls: false,
            lockMovementX: true,
            lockMovementY: true,
            selectable: false
          })
          rectText.top = centerPosition.centerY - rectText.height
          rectText.left = centerPosition.centerX - (rectText.width / 2)
          //console.log(7)

          //非0时使用配置的位置
          if (config.textX && config.textY && config.textX * 1 != 0 && config.textY * 1 != 0) {
            rectText.top = config.textY * -1
            rectText.left = config.textX * 1
          }

          //加偏移量
          if (config.textYOffset && config.textXOffset) {
            rectText.top = (rectText.top * 1 + config.textYOffset * -1)
            rectText.left = (rectText.left * 1 + config.textXOffset * 1)
          }
          //console.log(8)

          //自动换行
          if (config.fontWidth && config.fontWidth != 0) {
            rectText.width = config.fontWidth
            rectText.splitByGrapheme = true
          }
          //console.log(9)
          this.canvas.add(rectText)
        }

      }
      //console.log("结束")
    },

    //初始化Canvas
    intiCanvas() {
      this.canvas = new fabric.Canvas('canvas', {
        selection: false
        // originY: 'bottom'
      })
      this.canvas.setWidth(this.$refs.canvasParent.$el.offsetWidth)
      this.canvas.setHeight(this.$refs.canvasParent.$el.offsetHeight)

      this.canvas.preserveObjectStacking = true


      // 鼠标按下事件
      this.canvas.on('mouse:down', (options) => {
        this.canvasConfig.panning = true
      })

      // 鼠标抬起事件
      this.canvas.on('mouse:up', (options) => {
        this.canvasConfig.panning = false
      })

      // 移动画布事件
      this.canvas.on('mouse:move', (e) => {
        if (this.canvasConfig.panning && e && e.e) {
          let delta = new fabric.Point(e.e.movementX, e.e.movementY)
          this.canvas.relativePan(delta)
        }
      })

    },

    //缩放
    setZoom(zoomNum) {
      let zoom = zoomNum + (zoomNum === 0 ? 1 : this.canvas.getZoom())
      zoom = Math.max(this.canvasConfig.defaultZoom, zoom) // 最小为原来
      zoom = Math.min(3, zoom) // 最大是原来的3倍
      const zoomPoint = new fabric.Point(0, 0)
      this.canvas.zoomToPoint(zoomPoint, zoom)
    },

    resizeCanvas() {
      let canvas = this.canvas;
      //
      canvas.setWidth(this.$refs.canvasParent.$el.offsetWidth)
      canvas.setHeight(this.$refs.canvasParent.$el.offsetHeight)

      // 计算
      const [minX, minY, maxX, maxY] = this.calcBorder()

      // 平移
      const panX = (maxX - minX - canvas.width) / 2 + minX
      const panY = (maxY - minY - canvas.height) / 2 + minY
      canvas.absolutePan({x: panX, y: panY})

      //缩放
      let zoom = Math.min(canvas.width / (maxX - minX), canvas.height / (maxY - minY))

      //计算缩放中心
      let zoomPoint = new fabric.Point(canvas.width / 2, canvas.height / 2)

      //开始缩放
      canvas.zoomToPoint(zoomPoint, zoom)

      //
      this.canvasConfig.defaultZoom = zoom
      ////console.log(this.defaultZoom)
    },

    //计算宽高
    calcBorder() {
      let canvas = this.canvas
      //先还原缩放比例与位置
      canvas.setZoom(1)
      canvas.absolutePan({x: 0, y: 0})
      //遍历所有对对象，获取最小坐标，最大坐标
      let objects = canvas.getObjects()
      let rect = objects[0].getBoundingRect()
      let minX = rect.left
      let minY = rect.top
      let maxX = rect.left + rect.width
      let maxY = rect.top + rect.height
      if (objects.length > 0) {
        rect = objects[0].getBoundingRect()
        minX = rect.left
        minY = rect.top
        maxX = rect.left + rect.width
        maxY = rect.top + rect.height
        for (let i = 1; i < objects.length; i++) {
          rect = objects[i].getBoundingRect()
          minX = Math.min(minX, rect.left)
          minY = Math.min(minY, rect.top)
          maxX = Math.max(maxX, rect.left + rect.width)
          maxY = Math.max(maxY, rect.top + rect.height)
        }
      }
      return [minX, minY, maxX, maxY]
    },

    queryPage_() {
    },
    resetForm_() {
    },
    //
    fullScreen() {
    },
  }

});
</script>

<style lang="less">
</style>

<style scoped lang="less">

</style>
